import 'package:flutter/material.dart';
import '../../domain/entities/anime.dart';
import '../../domain/repositories/anime_repository.dart';
import '../../data/datasources/anime_local_datasource.dart'; // 添加缓存数据源
import '../../data/models/anime_model.dart'; // 添加AnimeModel导入
import 'content_filter_provider.dart';
import '../../core/utils/content_filter.dart';

/// 动漫状态管理Provider
class AnimeProvider extends ChangeNotifier {
  final AnimeRepository _repository;
  final AnimeLocalDataSource _localDataSource; // 添加缓存数据源
  final ContentFilterProvider _contentFilterProvider; // 内容过滤Provider

  AnimeProvider(this._repository, this._localDataSource, this._contentFilterProvider);

  // 状态变量
  List<Anime> _topAnime = [];
  List<Anime> _seasonalAnime = [];
  List<Anime> _upcomingAnime = []; // 即将上线动漫
  List<Anime> _trendingAnime = []; // 热门动漫
  List<Anime> _recentEpisodes = []; // 最新剧集动漫
  
  // 排行榜数据
  List<Anime> _rankingByScore = []; // 评分排行榜
  List<Anime> _rankingByPopularity = []; // 人气排行榜
  List<Anime> _rankingByMembers = []; // 收藏排行榜
  List<Anime> _rankingByFavorites = []; // 喜爱排行榜
  
  // 排行榜分页状态
  int _scoreCurrentPage = 1;
  int _popularityCurrentPage = 1;
  int _membersCurrentPage = 1;
  int _favoritesCurrentPage = 1;
  bool _isLoadingMore = false;
  
  bool _isLoading = false;
  bool _hasError = false;
  String _errorMessage = '';
  bool _isFirstLoad = true; // 是否首次加载

  // Getters
  List<Anime> get topAnime => _topAnime;
  List<Anime> get seasonalAnime => _seasonalAnime;
  List<Anime> get upcomingAnime => _upcomingAnime;
  List<Anime> get trendingAnime => _trendingAnime;
  List<Anime> get recentEpisodes => _recentEpisodes;
  
  // 排行榜 getters
  List<Anime> get rankingByScore => _rankingByScore;
  List<Anime> get rankingByPopularity => _rankingByPopularity;
  List<Anime> get rankingByMembers => _rankingByMembers;
  List<Anime> get rankingByFavorites => _rankingByFavorites;
  
  bool get isLoading => _isLoading;
  bool get isLoadingMore => _isLoadingMore;
  bool get hasError => _hasError;
  String get errorMessage => _errorMessage;
  bool get isFirstLoad => _isFirstLoad;

  /// 过滤动漫列表
  List<Anime> _filterAnimeList(List<Anime> animeList) {
    if (!_contentFilterProvider.isInitialized) {
      return animeList; // 如果过滤器未初始化，返回原列表
    }
    
    return _contentFilterProvider.filterAnimeList<Anime>(
      animeList,
      (anime) => anime.rating,
      (anime) => anime.genres,
      (anime) => anime.title,
      (anime) => anime.synopsis,
    );
  }

  /// 初始化数据 - 优先从缓存加载
  Future<void> initializeData() async {
    if (!_isFirstLoad) return;

    print('开始初始化数据...');
    _isFirstLoad = false;
    
    try {
      // 预热缓存，立即加载已有数据
      final cachedData = await _localDataSource.preloadHomePageCache();
      
      if (cachedData.isNotEmpty) {
        print('从缓存加载数据: ${cachedData.keys.join(', ')}');
        
        // 立即显示缓存数据（应用内容过滤）
        if (cachedData.containsKey('trending')) {
          final trendingList = cachedData['trending']!.map((model) => model.toEntity()).toList();
          _trendingAnime = _filterAnimeList(trendingList);
        }
        if (cachedData.containsKey('upcoming')) {
          final upcomingList = cachedData['upcoming']!.map((model) => model.toEntity()).toList();
          _upcomingAnime = _filterAnimeList(upcomingList);
        }
        if (cachedData.containsKey('seasonal')) {
          final seasonalList = cachedData['seasonal']!.map((model) => model.toEntity()).toList();
          _seasonalAnime = _filterAnimeList(seasonalList);
        }
        if (cachedData.containsKey('recent')) {
          final recentList = cachedData['recent']!.map((model) => model.toEntity()).toList();
          _recentEpisodes = _filterAnimeList(recentList);
        }
        
        notifyListeners();
        
        // 后台刷新数据
        _refreshDataInBackground();
      } else {
        // 没有缓存数据，正常加载
        print('没有缓存数据，正常加载...');
        await _loadAllData();
      }
    } catch (e) {
      print('初始化数据失败: $e');
      _setError('初始化数据失败: $e');
    }
  }

  /// 后台刷新所有数据
  void _refreshDataInBackground() {
    print('开始后台刷新数据...');
    
    // 延迟刷新，避免影响UI响应
    Future.delayed(const Duration(milliseconds: 800), () async {
      try {
        await Future.wait([
          _smartRefreshData('trending'),
          _smartRefreshData('upcoming'),
          _smartRefreshData('seasonal'),
          _smartRefreshData('recent'),
        ]);
        print('后台数据刷新完成');
        
        // 主页数据加载完成后，开始预加载排行榜数据
        _preloadRankingDataInBackground();
      } catch (e) {
        print('后台数据刷新失败: $e');
      }
    });
  }
  
  /// 后台预加载排行榜数据
  void _preloadRankingDataInBackground() {
    print('开始后台预加载排行榜数据...');
    
    // 延迟预加载，确保不影响主页体验
    Future.delayed(const Duration(seconds: 2), () async {
      try {
        // 只预加载评分排行榜（最常用的）
        if (_rankingByScore.isEmpty) {
          print('预加载评分排行榜...');
          await fetchRankingByScore();
        }
      } catch (e) {
        print('后台预加载排行榜失败: $e');
      }
    });
  }

  /// 智能刷新数据 - 只有当新数据与缓存不同时才更新UI
  Future<void> _smartRefreshData(String dataType) async {
    try {
      List<Anime> currentData = [];
      List<Anime> newData = [];
      
      // 获取当前显示的数据
      switch (dataType) {
        case 'trending':
          currentData = _trendingAnime;
          newData = await _repository.getTrendingAnime(forceRefresh: true);
          break;
        case 'upcoming':
          currentData = _upcomingAnime;
          newData = await _repository.getUpcomingAnime(forceRefresh: true);
          break;
        case 'seasonal':
          currentData = _seasonalAnime;
          newData = await _repository.getSeasonalAnime(forceRefresh: true);
          break;
        case 'recent':
          currentData = _recentEpisodes;
          newData = await _repository.getRecentEpisodes(forceRefresh: true);
          break;
      }
      
      // 应用内容过滤
      newData = _filterAnimeList(newData);
      
      // 比较数据是否有变化（比较ID列表和数量）
      final currentIds = currentData.map((anime) => anime.id).toList();
      final newIds = newData.map((anime) => anime.id).toList();
      
      // 检查是否有实质性变化
      bool hasChanges = currentIds.length != newIds.length ||
                       !_listsEqual(currentIds, newIds);
      
      if (hasChanges) {
        print('发现 $dataType 数据有更新，刷新UI');
        
        // 更新对应的数据
        switch (dataType) {
          case 'trending':
            _trendingAnime = newData;
            break;
          case 'upcoming':
            _upcomingAnime = newData;
            break;
          case 'seasonal':
            _seasonalAnime = newData;
            break;
          case 'recent':
            _recentEpisodes = newData;
            break;
        }
        
        // 通知UI更新
        notifyListeners();
      } else {
        print('$dataType 数据无变化，保持当前缓存');
      }
    } catch (e) {
      print('智能刷新 $dataType 失败: $e');
    }
  }

  /// 检查两个列表是否相等
  bool _listsEqual<T>(List<T> list1, List<T> list2) {
    if (list1.length != list2.length) return false;
    for (int i = 0; i < list1.length; i++) {
      if (list1[i] != list2[i]) return false;
    }
    return true;
  }

  /// 加载所有数据
  Future<void> _loadAllData() async {
    await Future.wait([
      fetchTrendingAnime(),
      fetchUpcomingAnime(),
      fetchSeasonalAnime(),
      fetchRecentEpisodes(),
    ]);
  }

  /// 获取热门动漫
  Future<void> fetchTopAnime({bool refresh = false}) async {
    if (_isLoading) return;

    if (refresh || _topAnime.isEmpty) {
      _setLoading(true);
      _clearError();

      try {
        final animeList = await _repository.getTopAnime(
          page: 1,
          filter: 'bypopularity',
        );
        
        _topAnime = _filterAnimeList(animeList);
        notifyListeners();
      } catch (e) {
        _setError('获取热门动漫失败: ${e.toString()}');
      } finally {
        _setLoading(false);
      }
    }
  }

  /// 获取即将上线动漫
  Future<void> fetchUpcomingAnime({
    bool refresh = false,
    bool silent = false,
  }) async {
    if (!silent) {
      _setLoading(true);
    }
    
    try {
      final animeList = await _repository.getUpcomingAnime();
      _upcomingAnime = _filterAnimeList(animeList);
      _clearError();
      
      if (!silent) {
        _setLoading(false);
      }
      notifyListeners();
    } catch (e) {
      if (!silent) {
        _setError('获取即将上线动漫失败: $e');
        _setLoading(false);
      }
    }
  }

  /// 获取最新最火的动漫 (替换原来的topAnime作为推荐)
  Future<void> fetchTrendingAnime({
    bool refresh = false,
    bool silent = false, // 静默刷新，不显示加载状态
  }) async {
    if (!silent) {
      _setLoading(true);
    }
    
    try {
      final animeList = await _repository.getTrendingAnime();
      _trendingAnime = _filterAnimeList(animeList);
      _clearError();
      
      if (!silent) {
        _setLoading(false);
      }
      notifyListeners();
    } catch (e) {
      if (!silent) {
        _setError('获取热门动漫失败: $e');
        _setLoading(false);
      }
    }
  }

  /// 获取当季动漫
  Future<void> fetchSeasonalAnime({
    int? year,
    String season = 'now',
    bool refresh = false,
    bool silent = false,
  }) async {
    if (!silent) {
      _setLoading(true);
    }
    
    try {
      final animeList = await _repository.getSeasonalAnime(
        year: year,
        season: season,
      );
      _seasonalAnime = _filterAnimeList(animeList);
      _clearError();
      
      if (!silent) {
        _setLoading(false);
      }
      notifyListeners();
    } catch (e) {
      if (!silent) {
        _setError('获取当季动漫失败: $e');
        _setLoading(false);
      }
    }
  }

  /// 搜索动漫
  Future<List<Anime>> searchAnime(String query, {int page = 1}) async {
    try {
      final animeList = await _repository.searchAnime(query: query, page: page);
      return _filterAnimeList(animeList);
    } catch (e) {
      _setError('搜索失败: ${e.toString()}');
      return [];
    }
  }

  /// 获取动漫详情
  Future<Anime?> getAnimeDetails(int animeId) async {
    try {
      return await _repository.getAnimeDetails(animeId);
    } catch (e) {
      _setError('获取详情失败: ${e.toString()}');
      return null;
    }
  }

  /// 获取智能推荐（结合API推荐和同类型推荐）
  Future<List<Anime>> getSmartRecommendations(Anime anime) async {
    try {
      final List<Anime> recommendations = [];
      
      // 1. 尝试获取API推荐
      try {
        final apiRecommendations = await _repository.getAnimeRecommendations(anime.id);
        recommendations.addAll(_filterAnimeList(apiRecommendations.take(3).toList()));
        print('API推荐获取成功: ${apiRecommendations.length}个');
      } catch (e) {
        print('API推荐获取失败: $e');
      }
      
      // 2. 寻找续作 - 通过标题关键词搜索
      if (recommendations.length < 6) {
        try {
          final sequelRecommendations = await _findSequels(anime);
          final filteredSequels = sequelRecommendations
              .where((rec) => 
                  rec.id != anime.id && 
                  !recommendations.any((existing) => existing.id == rec.id))
              .take(2)
              .toList();
          
          recommendations.addAll(_filterAnimeList(filteredSequels));
          if (filteredSequels.isNotEmpty) {
            print('续作推荐获取成功: ${filteredSequels.length}个');
          }
        } catch (e) {
          print('续作推荐获取失败: $e');
        }
      }
      
      // 3. 如果推荐不足，用同类型推荐补充
      if (recommendations.length < 6 && anime.genres.isNotEmpty) {
        // 获取第一个类型的动漫作为补充
        final primaryGenreId = _getGenreId(anime.genres.first);
        if (primaryGenreId != null) {
          try {
            final genreRecommendations = await _repository.getAnimeByGenre(
              genreId: primaryGenreId,
              page: 1,
              limit: 8,
            );
            
            // 过滤掉当前动漫和已有推荐
            final filteredGenreRecommendations = genreRecommendations
                .where((rec) => 
                    rec.id != anime.id && 
                    !recommendations.any((existing) => existing.id == rec.id))
                .take(6 - recommendations.length)
                .toList();
            
            recommendations.addAll(_filterAnimeList(filteredGenreRecommendations));
            if (filteredGenreRecommendations.isNotEmpty) {
              print('同类型推荐获取成功: ${filteredGenreRecommendations.length}个');
            }
          } catch (e) {
            print('同类型推荐获取失败: $e');
          }
        }
      }
      
      // 4. 如果还是不足，用热门动漫补充
      if (recommendations.length < 6) {
        try {
          final trendingRecommendations = _trendingAnime
              .where((rec) => 
                  rec.id != anime.id && 
                  !recommendations.any((existing) => existing.id == rec.id))
              .take(6 - recommendations.length)
              .toList();
          
          recommendations.addAll(trendingRecommendations);
          if (trendingRecommendations.isNotEmpty) {
            print('热门动漫推荐补充: ${trendingRecommendations.length}个');
          }
        } catch (e) {
          print('热门动漫推荐补充失败: $e');
        }
      }
      
      print('智能推荐完成，共${recommendations.length}个推荐');
      return recommendations.take(6).toList();
    } catch (e) {
      print('获取智能推荐失败: $e');
      return [];
    }
  }

  /// 寻找续作或相关系列作品
  Future<List<Anime>> _findSequels(Anime anime) async {
    try {
      // 提取主要标题关键词
      final keywords = _extractKeywords(anime.title);
      if (keywords.isEmpty) return [];
      
      // 搜索包含相同关键词的动漫
      final searchResults = await _repository.searchAnime(
        query: keywords.first,
        page: 1,
      );
      
      // 过滤出可能的续作
      final potentialSequels = searchResults.where((result) {
        // 排除自己
        if (result.id == anime.id) return false;
        
        // 检查是否有共同的制作公司
        final hasCommonStudio = anime.studios.any((studio) => 
            result.studios.contains(studio));
        
        // 检查是否有相似的类型
        final hasCommonGenre = anime.genres.any((genre) => 
            result.genres.contains(genre));
        
        // 检查标题相似度
        final hasSimilarTitle = _isSimilarTitle(anime.title, result.title);
        
        return (hasCommonStudio || hasCommonGenre) && hasSimilarTitle;
      }).toList();
      
      // 按评分排序
      potentialSequels.sort((a, b) => b.score.compareTo(a.score));
      
      return potentialSequels.take(2).toList();
    } catch (e) {
      print('寻找续作失败: $e');
      return [];
    }
  }

  /// 提取标题关键词
  List<String> _extractKeywords(String title) {
    // 移除常见的季度标识符和数字
    final cleanTitle = title
        .replaceAll(RegExp(r'\s+(Season|S)\s*\d+', caseSensitive: false), '')
        .replaceAll(RegExp(r'\s+(第\d+季|第二季|第三季|第四季)', caseSensitive: false), '')
        .replaceAll(RegExp(r'\s*\d+$'), '') // 移除末尾数字
        .replaceAll(RegExp(r'\s*(OVA|Movie|Special|Final|THE\s+FINAL)', caseSensitive: false), '')
        .trim();
    
    if (cleanTitle.isNotEmpty) {
      return [cleanTitle];
    }
    return [];
  }

  /// 检查标题相似度
  bool _isSimilarTitle(String title1, String title2) {
    final clean1 = _extractKeywords(title1).first.toLowerCase();
    final clean2 = _extractKeywords(title2).first.toLowerCase();
    
    // 检查是否包含相同的主要词汇
    return clean1.contains(clean2) || clean2.contains(clean1) || 
           _calculateSimilarity(clean1, clean2) > 0.7;
  }

  /// 计算字符串相似度（简单实现）
  double _calculateSimilarity(String a, String b) {
    if (a.isEmpty && b.isEmpty) return 1.0;
    if (a.isEmpty || b.isEmpty) return 0.0;
    
    final maxLength = a.length > b.length ? a.length : b.length;
    final minLength = a.length < b.length ? a.length : b.length;
    
    int commonChars = 0;
    for (int i = 0; i < minLength; i++) {
      if (a[i] == b[i]) {
        commonChars++;
      }
    }
    
    return commonChars / maxLength;
  }

  /// 根据类型名称获取类型ID
  int? _getGenreId(String genreName) {
    // 常见类型映射
    const genreMap = {
      '动作': 1,
      '冒险': 2,
      '喜剧': 4,
      '剧情': 8,
      '奇幻': 10,
      '历史': 13,
      '恐怖': 14,
      '悬疑': 7,
      '恋爱': 22,
      '科幻': 24,
      '日常': 36,
      '运动': 30,
      '超自然': 37,
      '惊悚': 41,
      '机械': 9,
      '音乐': 19,
      '校园': 23,
      '军事': 18,
      '武术': 17,
      '魔法': 16,
      '心理': 40,
      '太空': 29,
      // 英文映射
      'Action': 1,
      'Adventure': 2,
      'Comedy': 4,
      'Drama': 8,
      'Fantasy': 10,
      'Historical': 13,
      'Horror': 14,
      'Mystery': 7,
      'Romance': 22,
      'Sci-Fi': 24,
      'Slice of Life': 36,
      'Sports': 30,
      'Supernatural': 37,
      'Thriller': 41,
      'Mecha': 9,
      'Music': 19,
      'School': 23,
      'Military': 18,
      'Martial Arts': 17,
      'Magic': 16,
      'Psychological': 40,
      'Space': 29,
    };
    
    return genreMap[genreName];
  }

  /// 手动刷新所有数据
  Future<void> refreshAllData() async {
    _setLoading(true);
    
    try {
      // 手动刷新时强制获取新数据并对比
      final List<Future<void>> refreshTasks = [
        _smartRefreshData('trending'),
        _smartRefreshData('upcoming'),
        _smartRefreshData('seasonal'),
        _smartRefreshData('recent'),
      ];
      
      await Future.wait(refreshTasks);
      
      _clearError();
      print('手动刷新完成');
    } catch (e) {
      _setError('刷新数据失败: $e');
    } finally {
      _setLoading(false);
    }
  }

  /// 清除缓存
  Future<void> clearCache() async {
    try {
      await _repository.clearCache();
      _topAnime.clear();
      _seasonalAnime.clear();
      _upcomingAnime.clear();
      _trendingAnime.clear();
      
      // 清除排行榜数据
      _rankingByScore.clear();
      _rankingByPopularity.clear();
      _rankingByMembers.clear();
      _rankingByFavorites.clear();
      
      // 重置分页状态
      _resetRankingPages();
      
      notifyListeners();
    } catch (e) {
      _setError('清除缓存失败: ${e.toString()}');
    }
  }

  /// 根据分类获取动漫
  Future<List<Anime>> getAnimeByGenre({
    required int genreId,
    int page = 1,
    int limit = 20,
  }) async {
    try {
      final animeList = await _repository.getAnimeByGenre(
        genreId: genreId,
        page: page,
        limit: limit,
      );
      return _filterAnimeList(animeList);
    } catch (e) {
      _setError('获取分类动漫失败: ${e.toString()}');
      return [];
    }
  }

  /// 根据状态获取动漫
  Future<List<Anime>> getAnimeByStatus({
    required String status,
    int page = 1,
    int limit = 20,
  }) async {
    try {
      final animeList = await _repository.getAnimeByStatus(
        status: status,
        page: page,
        limit: limit,
      );
      return _filterAnimeList(animeList);
    } catch (e) {
      _setError('获取状态动漫失败: ${e.toString()}');
      return [];
    }
  }

  /// 根据类型获取动漫
  Future<List<Anime>> getAnimeByType({
    required String type,
    int page = 1,
    int limit = 20,
  }) async {
    try {
      final animeList = await _repository.getAnimeByType(
        type: type,
        page: page,
        limit: limit,
      );
      return _filterAnimeList(animeList);
    } catch (e) {
      _setError('获取类型动漫失败: ${e.toString()}');
      return [];
    }
  }

  /// 获取热门动漫列表（用于分类页面）
  Future<List<Anime>> getTopAnime({
    int page = 1,
    String filter = 'bypopularity',
    int limit = 25,
  }) async {
    try {
      final animeList = await _repository.getTopAnime(
        page: page, 
        filter: filter,
        limit: limit,
      );
      return _filterAnimeList(animeList);
    } catch (e) {
      _setError('获取热门动漫失败: ${e.toString()}');
      return [];
    }
  }

  /// 设置加载状态
  void _setLoading(bool loading) {
    _isLoading = loading;
    notifyListeners();
  }

  /// 设置错误状态
  void _setError(String message) {
    _hasError = true;
    _errorMessage = message;
    notifyListeners();
  }

  /// 清除错误状态
  void _clearError() {
    _hasError = false;
    _errorMessage = '';
  }

  /// 获取评分排行榜 (使用top anime，默认按评分排序)
  Future<void> fetchRankingByScore({bool refresh = false, int page = 1}) async {
    if (refresh || (page == 1 && _rankingByScore.isEmpty)) {
      if (refresh || page == 1) {
        _rankingByScore.clear(); // 刷新或首次加载时清空列表
      }
      
      try {
        // 首次加载时优先使用缓存
        if (page == 1 && !refresh) {
          final cachedData = await _localDataSource.getCachedRankingData('score');
          if (cachedData.isNotEmpty) {
            final cachedEntities = cachedData.map((model) => model.toEntity()).toList();
            _rankingByScore = _filterAnimeList(cachedEntities);
            notifyListeners();
            
            // 后台刷新数据
            _refreshRankingInBackground('score');
            return;
          }
        }
        
        final animeList = await _repository.getTopAnime(
          page: page,
          filter: '', // 不使用filter，获取默认的top anime (按评分排序)
        );
        
        // 缓存第一页数据
        if (page == 1) {
          final animeModels = animeList.map((entity) => AnimeModel.fromEntity(entity)).toList();
          await _localDataSource.cacheRankingData('score', animeModels);
        }
        
        final filteredList = _filterAnimeList(animeList);
        if (page == 1) {
          _rankingByScore = filteredList;
        } else {
          _rankingByScore.addAll(filteredList); // 追加新数据
        }
        notifyListeners();
      } catch (e) {
        _setError('获取评分排行榜失败: ${e.toString()}');
      }
    }
  }

  /// 获取人气排行榜 (使用bypopularity filter)
  Future<void> fetchRankingByPopularity({bool refresh = false, int page = 1}) async {
    if (refresh || (page == 1 && _rankingByPopularity.isEmpty)) {
      if (refresh || page == 1) {
        _rankingByPopularity.clear();
      }
      
      try {
        // 首次加载时优先使用缓存
        if (page == 1 && !refresh) {
          final cachedData = await _localDataSource.getCachedRankingData('popularity');
          if (cachedData.isNotEmpty) {
            final cachedEntities = cachedData.map((model) => model.toEntity()).toList();
            _rankingByPopularity = _filterAnimeList(cachedEntities);
            notifyListeners();
            
            // 后台刷新数据
            _refreshRankingInBackground('popularity');
            return;
          }
        }
        
        final animeList = await _repository.getTopAnime(
          page: page,
          filter: 'bypopularity', // 按人气排序
        );
        
        // 缓存第一页数据
        if (page == 1) {
          final animeModels = animeList.map((entity) => AnimeModel.fromEntity(entity)).toList();
          await _localDataSource.cacheRankingData('popularity', animeModels);
        }
        
        final filteredList = _filterAnimeList(animeList);
        if (page == 1) {
          _rankingByPopularity = filteredList;
        } else {
          _rankingByPopularity.addAll(filteredList);
        }
        notifyListeners();
      } catch (e) {
        _setError('获取人气排行榜失败: ${e.toString()}');
      }
    }
  }

  /// 获取当前播放排行榜 (使用airing filter)
  Future<void> fetchRankingByMembers({bool refresh = false, int page = 1}) async {
    if (refresh || (page == 1 && _rankingByMembers.isEmpty)) {
      if (refresh || page == 1) {
        _rankingByMembers.clear();
      }
      
      try {
        // 首次加载时优先使用缓存
        if (page == 1 && !refresh) {
          final cachedData = await _localDataSource.getCachedRankingData('airing');
          if (cachedData.isNotEmpty) {
            final cachedEntities = cachedData.map((model) => model.toEntity()).toList();
            _rankingByMembers = _filterAnimeList(cachedEntities);
            notifyListeners();
            
            // 后台刷新数据
            _refreshRankingInBackground('airing');
            return;
          }
        }
        
        final animeList = await _repository.getTopAnime(
          page: page,
          filter: 'airing', // 当前播放的动漫
        );
        
        // 缓存第一页数据
        if (page == 1) {
          final animeModels = animeList.map((entity) => AnimeModel.fromEntity(entity)).toList();
          await _localDataSource.cacheRankingData('airing', animeModels);
        }
        
        final filteredList = _filterAnimeList(animeList);
        if (page == 1) {
          _rankingByMembers = filteredList;
        } else {
          _rankingByMembers.addAll(filteredList);
        }
        notifyListeners();
      } catch (e) {
        _setError('获取当前播放排行榜失败: ${e.toString()}');
      }
    }
  }

  /// 获取喜爱排行榜 (使用favorite filter)
  Future<void> fetchRankingByFavorites({bool refresh = false, int page = 1}) async {
    if (refresh || (page == 1 && _rankingByFavorites.isEmpty)) {
      if (refresh || page == 1) {
        _rankingByFavorites.clear();
      }
      
      try {
        // 首次加载时优先使用缓存
        if (page == 1 && !refresh) {
          final cachedData = await _localDataSource.getCachedRankingData('favorites');
          if (cachedData.isNotEmpty) {
            final cachedEntities = cachedData.map((model) => model.toEntity()).toList();
            _rankingByFavorites = _filterAnimeList(cachedEntities);
            notifyListeners();
            
            // 后台刷新数据
            _refreshRankingInBackground('favorites');
            return;
          }
        }
        
        final animeList = await _repository.getTopAnime(
          page: page,
          filter: 'favorite', // 按喜爱数排序
        );
        
        // 缓存第一页数据
        if (page == 1) {
          final animeModels = animeList.map((entity) => AnimeModel.fromEntity(entity)).toList();
          await _localDataSource.cacheRankingData('favorites', animeModels);
        }
        
        final filteredList = _filterAnimeList(animeList);
        if (page == 1) {
          _rankingByFavorites = filteredList;
        } else {
          _rankingByFavorites.addAll(filteredList);
        }
        notifyListeners();
      } catch (e) {
        _setError('获取喜爱排行榜失败: ${e.toString()}');
      }
    }
  }

  /// 获取全部排行榜数据 - 优化版本，支持懒加载
  Future<void> fetchAllRankings({bool refresh = false, bool lazyLoad = true}) async {
    if (refresh) {
      _resetRankingPages(); // 刷新时重置页码
    }
    
    if (lazyLoad) {
      // 懒加载模式：只加载评分排行榜，其他的在需要时加载
      await fetchRankingByScore(refresh: refresh);
    } else {
      // 全量加载模式
    await Future.wait([
      fetchRankingByScore(refresh: refresh),
      fetchRankingByPopularity(refresh: refresh),
      fetchRankingByMembers(refresh: refresh),
      fetchRankingByFavorites(refresh: refresh),
    ]);
    }
  }
  
  /// 按需加载特定类型的排行榜
  Future<void> fetchRankingByType(String type, {bool refresh = false}) async {
    switch (type) {
      case 'score':
        await fetchRankingByScore(refresh: refresh);
        break;
      case 'popularity':
        await fetchRankingByPopularity(refresh: refresh);
        break;
      case 'airing':
        await fetchRankingByMembers(refresh: refresh);
        break;
      case 'favorites':
        await fetchRankingByFavorites(refresh: refresh);
        break;
    }
  }
  
  /// 后台刷新排行榜数据
  void _refreshRankingInBackground(String type) {
    Future.delayed(const Duration(milliseconds: 1000), () async {
      try {
        List<Anime> newData = [];
        
        switch (type) {
          case 'score':
            newData = await _repository.getTopAnime(page: 1, filter: '');
            break;
          case 'popularity':
            newData = await _repository.getTopAnime(page: 1, filter: 'bypopularity');
            break;
          case 'airing':
            newData = await _repository.getTopAnime(page: 1, filter: 'airing');
            break;
          case 'favorites':
            newData = await _repository.getTopAnime(page: 1, filter: 'favorite');
            break;
        }
        
        // 缓存新数据
        final animeModels = newData.map((entity) => AnimeModel.fromEntity(entity)).toList();
        await _localDataSource.cacheRankingData(type, animeModels);
        
        // 应用过滤并检查是否有变化
        final filteredData = _filterAnimeList(newData);
        List<Anime> currentData = [];
        
        switch (type) {
          case 'score':
            currentData = _rankingByScore;
            break;
          case 'popularity':
            currentData = _rankingByPopularity;
            break;
          case 'airing':
            currentData = _rankingByMembers;
            break;
          case 'favorites':
            currentData = _rankingByFavorites;
            break;
        }
        
        // 比较数据是否有变化
        final currentIds = currentData.map((anime) => anime.id).toList();
        final newIds = filteredData.map((anime) => anime.id).toList();
        
        if (currentIds.length != newIds.length || !_listsEqual(currentIds, newIds)) {
          // 有变化时更新数据
          switch (type) {
            case 'score':
              _rankingByScore = filteredData;
              break;
            case 'popularity':
              _rankingByPopularity = filteredData;
              break;
            case 'airing':
              _rankingByMembers = filteredData;
              break;
            case 'favorites':
              _rankingByFavorites = filteredData;
              break;
          }
          notifyListeners();
        }
        
      } catch (e) {
        debugPrint('后台刷新排行榜 $type 失败: $e');
      }
    });
  }

  /// 加载更多评分排行榜数据
  Future<void> loadMoreRankingByScore() async {
    if (_isLoadingMore) return;
    
    _isLoadingMore = true;
    notifyListeners();
    
    try {
      _scoreCurrentPage++;
      await fetchRankingByScore(page: _scoreCurrentPage);
    } catch (e) {
      _scoreCurrentPage--; // 回滚页码
      _setError('加载更多评分排行榜失败: ${e.toString()}');
    } finally {
      _isLoadingMore = false;
      notifyListeners();
    }
  }

  /// 加载更多人气排行榜数据
  Future<void> loadMoreRankingByPopularity() async {
    if (_isLoadingMore) return;
    
    _isLoadingMore = true;
    notifyListeners();
    
    try {
      _popularityCurrentPage++;
      await fetchRankingByPopularity(page: _popularityCurrentPage);
    } catch (e) {
      _popularityCurrentPage--;
      _setError('加载更多人气排行榜失败: ${e.toString()}');
    } finally {
      _isLoadingMore = false;
      notifyListeners();
    }
  }

  /// 加载更多当前播放排行榜数据
  Future<void> loadMoreRankingByMembers() async {
    if (_isLoadingMore) return;
    
    _isLoadingMore = true;
    notifyListeners();
    
    try {
      _membersCurrentPage++;
      await fetchRankingByMembers(page: _membersCurrentPage);
    } catch (e) {
      _membersCurrentPage--;
      _setError('加载更多当前播放排行榜失败: ${e.toString()}');
    } finally {
      _isLoadingMore = false;
      notifyListeners();
    }
  }

  /// 加载更多喜爱排行榜数据
  Future<void> loadMoreRankingByFavorites() async {
    if (_isLoadingMore) return;
    
    _isLoadingMore = true;
    notifyListeners();
    
    try {
      _favoritesCurrentPage++;
      await fetchRankingByFavorites(page: _favoritesCurrentPage);
    } catch (e) {
      _favoritesCurrentPage--;
      _setError('加载更多喜爱排行榜失败: ${e.toString()}');
    } finally {
      _isLoadingMore = false;
      notifyListeners();
    }
  }

  /// 重置排行榜分页状态
  void _resetRankingPages() {
    _scoreCurrentPage = 1;
    _popularityCurrentPage = 1;
    _membersCurrentPage = 1;
    _favoritesCurrentPage = 1;
  }

  /// 获取最新剧集动漫
  Future<void> fetchRecentEpisodes({
    bool silent = false,
  }) async {
    if (!silent) {
      _setLoading(true);
    }
    
    try {
      print('开始获取最新剧集数据...');
      final animeList = await _repository.getRecentEpisodes(limit: 15);
      print('获取到原始数据: ${animeList.length} 个');
      
      _recentEpisodes = _filterAnimeList(animeList);
      print('过滤后数据: ${_recentEpisodes.length} 个');
      
      _clearError();
      
      if (!silent) {
        _setLoading(false);
      }
      notifyListeners();
    } catch (e) {
      print('获取最新剧集失败: $e');
      if (!silent) {
        _setError('获取最新剧集失败: $e');
        _setLoading(false);
      }
    }
  }

  /// 清除所有缓存
  Future<void> clearAllCache() async {
    await clearCache();
    await fetchRecentEpisodes();
  }

  /// 检查缓存状态
  Future<Map<String, bool>> getCacheStatus() async {
    return await _localDataSource.getHomePageCacheStatus();
  }
} 